﻿using System;
using NHibernate;


namespace SqlDALLibrary
{
    public class EntityControl
    {
        private static EntityControl entity;
        private string _AssemblyName;
        static readonly object padlock = new object();

        public static EntityControl CreateEntityControl(string AssemblyName)
        {
            if (entity == null)
            {
                lock (padlock)
                {
                    if (entity == null)
                    {
                        entity = new EntityControl();
                        entity._AssemblyName = AssemblyName;
                    }
                }
            }
            return entity;
        }

        public void AddEntity(Object entity)
        {
            ISession session = SessionFactory.OpenSession(_AssemblyName);
            ITransaction transaction = session.BeginTransaction();
            try
            {
                session.Save(entity);
                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                throw ex;
            }
            finally
            {
                session.Close();
            }
        }

        public void UpdateEntity(Object entity, Object key)
        {
            ISession session = SessionFactory.OpenSession(_AssemblyName);
            ITransaction transaction = session.BeginTransaction();
            try
            {
                session.Update(entity);
                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                throw ex;
            }
            finally
            {
                session.Close();
            }
        }

        public void DeleteEntity(object entity)
        {
            ISession session = SessionFactory.OpenSession(_AssemblyName);
            ITransaction transaction = session.BeginTransaction();

            try
            {
                session.Delete(entity);
                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                throw ex;
            }
            finally
            {
                session.Close();
            }
        }

        public ISession getSession()
        {
            return SessionFactory.OpenSession(_AssemblyName); ;
        }


    }
}
